using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using NiSis.Data;
using NiSis.Entities;
using NiSis.UserControls;
using NiSis.Loggin;

namespace NiSis
{
    public partial class Guess : System.Web.UI.Page
    {
        private VList<VTradersPrec> msTraders = new VList<VTradersPrec>();
        VList<VTradersPrec> sTraders
        {
            get
            {
                if (msTraders.Count == 0 && Session["msTraders"] == null)
                    return msTraders;
                if (msTraders.Count == 0 && Session["msTraders"] != null)
                    msTraders = (VList<VTradersPrec>) Session["msTraders"];
                
                return msTraders;
            }
            set
            {
                //can't be set to an empty chain, that has to be done explicitly
                VList<VTradersPrec> tempValue = value;
                if (tempValue.Count == 0)
                    return;

                msTraders = tempValue;
                
                Session["msTraders"] = msTraders;
            }
        }
        /// <summary>
        /// explicit call in order to clear the session value (it's the only allowed way to do it)
        /// </summary>
        protected void ClearSTrader()
        {
            msTraders = new VList<VTradersPrec>();
            Session["msTraders"] = msTraders;
        }
        VTradersPrec CurrentPool;


        protected void Page_Load(object sender, EventArgs e)
        {
            PnlSuccess.Visible = false;
            pnlError.Visible = false;
            if (!Page.IsPostBack)
            {
                if (Request["cdpool"] != null)
                {
                    GotoTraderPrec();
                    cmdOk.Visible = false;
                }
                if (Request["idbatch"] != null)
                {
                    Wizard1.ActiveStepIndex = 3;
                    RelationshipPicker1.LoadBatch(int.Parse(Request["idbatch"]));
                    cmdOk.Visible = false;
                }      
            }
        }
        /// <summary>
        /// Interpreta la request e salta al traderprecadeguato
        /// </summary>
        private void GotoTraderPrec()
        {
            VList<VTradersPrec> tprecs = new VList<VTradersPrec>();
            VTradersPrec tprec = new VTradersPrec();
            tprec.CdPool = Request["cdpool"] ?? string.Empty;
            tprec.CdMeseInizioFornitura = Request["cdmese"] ?? string.Empty;
            tprec.CdTraderPrecedente = Request["traderprec"] ?? string.Empty;
            tprec.CdCliente = Request["cdcliente"] ?? string.Empty;
            tprec.DsCliente = Request["dscliente"] ?? string.Empty;
            tprec.DsSocieta = Request["dssocieta"] ?? string.Empty;
            tprec.CdPuntoFornitura = Request["cdpunto"] ?? string.Empty;
            tprec.CdComune = Request["cdcomune"] ?? string.Empty;
            tprec.ConsumoAnnuoStimato = Request["cdconsumo"] ?? string.Empty;
            tprec.CdPrelievoAeeg = Request["cdprelievo"] ?? string.Empty;

            tprec.IdStatoLavorazioneUtenza = 1;
            tprecs.Add(tprec);
            Wizard1.ActiveStepIndex = 3;
            
            if (tprec.CdCliente != string.Empty)
                RelationshipPicker1.LoadBatchWithPartialUsers(tprecs, true);
            else
                RelationshipPicker1.LoadBatch(tprecs, true);
        }
        private SmartNavigator mNavigator;

        public SmartNavigator Navigator
        {
            get
            {

                if (mNavigator == null && Session["SNavigator"] != null)
                {
                    mNavigator = (SmartNavigator)Session["SNavigator"];
                    return mNavigator;
                }

                return mNavigator;
            }
            set 
            {
                if (value == null)
                    return;
                mNavigator = value;
                Session["SNavigator"] = mNavigator;
            }
        }
	
        protected void PoolsToActivate1_Load(object sender, EventArgs e)
        {

        }

        protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
        {

        }

        protected void StartNextButton_Click(object sender, EventArgs e)
        {
            
            
            CurrentPool = PoolsToActivate1.GetCurrentPool();
            if (CurrentPool == null)
            {
                Wizard1.ActiveStepIndex = 0;
                return;
            }
            if (Navigator == null)
                Navigator = new SmartNavigator();

            Navigator.CdPool = CurrentPool.CdPool;
            Navigator.CdMeseAnno = CurrentPool.CdMeseInizioFornitura;
            Navigator.targetState = 0;
            PrecTraders1.LoadTraders(CurrentPool.CdPool,CurrentPool.CdMeseInizioFornitura);
        }

        protected void StepPreviousButton_Click(object sender, EventArgs e)
        {
            if (Wizard1.ActiveStepIndex == 1)
                PoolsToActivate1.Refresh();

        }
        protected void Wizard1_NextButtonClick(object sender, WizardNavigationEventArgs e)
        {
            switch (e.CurrentStepIndex)
            {
                case 0:
                    e.Cancel =(!PoolsToActivate1.CanGoNext());
                    break;
                case 1:
                    if (!PrecTraders1.AreRowSelected())
                    {

                        MsgBox("Si deve al meno selezionare una trader per proseguire");
                        e.Cancel = true;
                        return;

                    }
                    if (!PrecTraders1.SelectionIsComplete() && sTraders.Count != 0)
                    {
                        Navigator.CdMeseAnno = sTraders[0].CdMeseInizioFornitura;
                        Navigator.CdPool = sTraders[0].CdPool;
                        Navigator.targetState = 1;
                    }
                    else
                    {
                        Navigator.targetState = 0;
                    }

                    
                    if ( sTraders.Count == 1 && PrecTraders1.ShowUsers)
                    {

                        Navigator.CdTraderPrec = sTraders[0].CdTraderPrecedente ?? string.Empty;
                        Navigator.DsTraderPrec = sTraders[0].DsSocieta ?? string.Empty;

                        DettaglioUtenze1.CurrentTp = sTraders[0].CdTraderPrecedente ?? string.Empty;
                        DettaglioUtenze1.LoadUtenze(CurrentPool.CdPool,
                            sTraders[0].CdTraderPrecedente ?? string.Empty,
                            sTraders[0].DsSocieta ?? string.Empty,CurrentPool.CdMeseInizioFornitura);

                        return;

                    }
                   
                    else
                    {
                        RelationshipPicker1.CheckForRed = PrecTraders1.IsRedInselected();

                        if ( sTraders.Count == 1)
                            RelationshipPicker1.CurrentCdTraderPrecedente = sTraders[0].CdTraderPrecedente ?? string.Empty;
                        Wizard1.ActiveStepIndex = 3;
                        RelationshipPicker1.LoadBatch(sTraders, ! PrecTraders1.IsNonIpotizzatoInSelected());

                    }
                    break;
                case 2:
                    if (DettaglioUtenze1.GetSelectedUtenze(CurrentPool.CdTraderPrecedente, CurrentPool.CdPool,CurrentPool.CdMeseInizioFornitura).Count == 0)
                    {
                        MsgBox("Si deve al meno selezionare una utenza per proseguire");
                        e.Cancel=true;
                        return;
                    }
                    if (!DettaglioUtenze1.SelectionIsComplete())
                        Navigator.targetState = 2;
                    else if (DettaglioUtenze1.SelectionIsComplete() && !PrecTraders1.SelectionIsComplete(DettaglioUtenze1.CurrentTp))
                        Navigator.targetState = 1;
                    else
                        Navigator.targetState = 0;

                    //RelationshipPicker1.CheckForRed = DettaglioUtenze1.IsRedInselected();
                    RelationshipPicker1.CheckForRed = true;
                    if (sTraders.Count > 1)
                        RelationshipPicker1.LoadBatch(sTraders, ! PrecTraders1.IsNonIpotizzatoInSelected());
                    else
                    {
                        RelationshipPicker1.CurrentCdTraderPrecedente = sTraders[0].CdTraderPrecedente ?? string.Empty;
                        RelationshipPicker1.LoadBatchWithPartialUsers(DettaglioUtenze1.GetSelectedUtenze(sTraders[0].CdTraderPrecedente, CurrentPool.CdPool, CurrentPool.CdMeseInizioFornitura),
                            (! DettaglioUtenze1.IsNonIpotizzatoInSelected()));
                    }
                    
                    break;

                default:
                    break;
            }
        }

        protected void Wizard1_PreviousButtonClick(object sender, WizardNavigationEventArgs e)
        {
            if (e.NextStepIndex == 0)
            {
               CurrentPool = null;
               RelationshipPicker1.Relazioni = null;
            }
            
        }

        protected void StepNextButton_Click(object sender, EventArgs e)
        {
            CurrentPool = PoolsToActivate1.GetCurrentPool();
            sTraders = PrecTraders1.GetSelectedTraders(CurrentPool.CdPool,CurrentPool.CdMeseInizioFornitura);

        }

        protected void FinishPreviousButton_Click(object sender, EventArgs e)
        {

        }

        protected void FinishButton_Click(object sender, EventArgs e)
        {
            try
            {
                RelationshipPicker1.Save();
                Wizard1.Enabled = false;
                PnlSuccess.Visible = true;
                Logger.Conferma("Operazione: ippotizzazione utenze, esito: successo");
                
            }
            catch (Exception ex)
            {
                Logger.ErroreGrave("Operazione: ippotizzazione utenze, esito: Errore nella ipotizzazione", ex);
                lblError.Text = String.Format("{0} {1}", lblError.Text, ex.Message);
                pnlError.Visible = true;
                
            }


        }

        protected void MsgBox(string msg)
        {
            ((NiSis)this.Master).MsgBox(msg);
        }

        protected void RelationshipPicker_StateChanged(object sender,RelationshipPicker.CompleteStateChangedEventArgs e)
        {
            Button btn = (Button)Wizard1.FindControl("FinishNavigationTemplateContainerID").FindControl("FinishButton");
            btn.Enabled = e.NewState == 1;
            
        }

        protected void cmdOk_Click(object sender, EventArgs e)
        {
            Session["BatchCurrentRelations"] = null;
            Wizard1.Enabled = true;
            RelationshipPicker1.Reset();
            PrecTraders1.LoadTraders(Navigator.CdPool,Navigator.CdMeseAnno);
           
            //Wizard1.ActiveStepIndex = Navigator.targetState;
            SetStep(Navigator);
        }


        protected void SetStep(SmartNavigator nav)
        {
            switch (nav.targetState)
            {
                case 0:
                    Wizard1.ActiveStepIndex = 0;
                    PoolsToActivate1.Refresh();
                    break;
                case 1:
                    PrecTraders1.LoadTraders(Navigator.CdPool,Navigator.CdMeseAnno);
                    Wizard1.ActiveStepIndex = nav.targetState;
                    break;
                case 2:
                    DettaglioUtenze1.LoadUtenze(nav.CdPool, nav.CdTraderPrec, nav.DsTraderPrec, nav.CdMeseAnno);
                    Wizard1.ActiveStepIndex = nav.targetState;
                    break;
                default:
                    break;
            }
        }


    }
}
